<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            label-width="68px"
        >
            <!-- <el-form-item label="题目简称" prop="varTitle">
                <el-input
                    v-model="queryParams.varTitle"
                    placeholder="请输入"
                    clearable
                    size="small"
                />
            </el-form-item> -->
            <el-form-item label="题目类型" prop="chrType">
                <el-select
                    v-model="queryParams.chrType"
                    placeholder="请选择试题类型"
                    :style="{ width: '100%' }"
                >
                    <el-option
                        v-for="item in chrTypeOptions"
                        :key="item.dictCode"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >搜索</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-if="jurisdiction"
                    >新增</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['system:question:remove']"
                    v-if="jurisdiction"
                    >删除</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="info"
                    icon="el-icon-upload2"
                    size="mini"
                    @click="handleImport"
                    v-if="jurisdiction"
                    >导入</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="warning"
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                    v-hasPermi="['system:question:export']"
                    >导出</el-button
                >
            </el-col>
        </el-row>

        <el-table
            v-loading="loading"
            :data="questionList"
            @selection-change="handleSelectionChange"
        >
            <el-table-column
                type="selection"
                width="55"
                align="center"
                v-if="jurisdiction"
            />
            <el-table-column label="试题编号" align="center" prop="varNo" />
            <!-- <el-table-column label="题目简称" align="center" prop="varTitle" /> -->
            <el-table-column align="center" label="题干" width="400">
                <template slot-scope="scope">
                    <el-popover placement="right" width="400" trigger="hover">
                        <div>
                            <div class="history-preview">
                                <label>试题内容:</label>
                                <div>
                                    <p
                                        v-html="
                                            JSON.parse(scope.row.varContent)
                                                .title
                                        "
                                    ></p>
                                    <!-- <div
                                        class="title-img"
                                        v-if="
                                            JSON.parse(scope.row.varContent)
                                                .fileInfo
                                        "
                                    >
                                        <span
                                            v-for="(item, index) in JSON.parse(
                                                scope.row.questionImg
                                            )"
                                            :key="index"
                                        >
                                            <img :src="item.fileId" />
                                        </span>
                                    </div> -->
                                </div>
                            </div>
                            <div class="history-preview">
                                <label>选项:</label>
                                <div>
                                    <div
                                        v-for="(data, index) in JSON.parse(
                                            scope.row.varContent
                                        ).options"
                                        :key="index"
                                        class="question-content"
                                    >
                                        <div>
                                            <span style="margin-right:5px;"
                                                >{{ data.item }} .</span
                                            >
                                            <p
                                                v-if="data.itemDesc"
                                                v-html="data.itemDesc"
                                            ></p>
                                        </div>
                                        <div
                                            class="question-img"
                                            v-if="data.fileInfo"
                                        >
                                            <span>
                                                <img
                                                    :src="
                                                        JSON.parse(
                                                            data.fileInfo
                                                        ).fileId
                                                    "
                                                />
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <p
                            v-html="JSON.parse(scope.row.varContent).title"
                            style="cursor: pointer;"
                            slot="reference"
                        ></p>
                    </el-popover>
                </template>
            </el-table-column>
            <!-- <el-table-column
                label="试题类型"
                align="center"
                prop="chrCategory"
            /> -->
            <el-table-column label="题目类型" align="center" prop="chrType" />
            <el-table-column label="试题答案" align="center" prop="varAnswer" />
            <el-table-column
                label="适用行业"
                align="center"
                prop="varIndustry"
            />
            <el-table-column
                label="创建时间"
                align="center"
                prop="createTime"
                width="100px"
            />
            <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
            >
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:question:edit']"
                        v-if="jurisdiction"
                        >修改</el-button
                    >
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['system:question:remove']"
                        v-if="jurisdiction"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改试题管理对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="580px"
            append-to-body
        >
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item
                    label="题目编号"
                    prop="varNo"
                    v-if="title != '新增试题管理'"
                >
                    <el-input
                        v-model="form.varNo"
                        disabled
                        placeholder="请输入题号"
                    />
                </el-form-item>
                <!-- <el-form-item label="题目简称" prop="varTitle">
                    <el-input
                        v-model="form.varTitle"
                        placeholder="请输入题目简称"
                    />
                </el-form-item> -->
                <div v-if="form.varContent">
                    <el-form-item label="题目标题" prop="varContent.title">
                        <el-row>
                            <el-col :span="19">
                                <el-input
                                    v-model="form.varContent.title"
                                    placeholder="请输入题目内容"
                                />
                            </el-col>
                            <el-col
                                :span="4"
                                v-show="form.varContent.options.length == 0"
                            >
                                <el-button @click="addOption"
                                    >新增选项</el-button
                                >
                            </el-col>
                        </el-row>
                    </el-form-item>
                    <el-form-item
                        :label="item.item"
                        v-for="(item, index) in form.varContent.options"
                        :key="item.item"
                        :prop="'varContent.options[' + index + '].itemDesc'"
                        :rules="[
                            {
                                required: true,
                                message: '选项不能为空',
                                trigger: 'blur'
                            }
                        ]"
                    >
                        <el-row>
                            <el-col :span="15">
                                <el-input
                                    v-model="item.itemDesc"
                                    placeholder="请输入选项内容"
                                />
                            </el-col>
                            <el-col :span="4">
                                <el-button @click="deleteOption(index)"
                                    >删除</el-button
                                >
                            </el-col>
                            <el-col
                                :span="5"
                                v-show="
                                    index == form.varContent.options.length - 1
                                "
                            >
                                <el-button @click="addOption"
                                    >新增选项</el-button
                                >
                            </el-col>
                        </el-row>
                    </el-form-item>
                </div>
                <!-- <el-form-item label="试题类型" prop="chrCategory">
                    <el-select
                        v-model="form.chrCategory"
                        placeholder="请选择试题类型"
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="item in chrCategoryOptions"
                            :key="item.dictCode"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                        ></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="题目类型" prop="chrType">
                    <el-select
                        v-model="form.chrType"
                        placeholder="请选择题目类型"
                        :style="{ width: '100%' }"
                        @change="chrTypeChange"
                    >
                        <el-option
                            v-for="item in chrTypeOptions"
                            :key="item.dictCode"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="适用行业" prop="varIndustry">
                    <el-select
                        v-model="form.varIndustry"
                        placeholder="请选择"
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="item in varIndustryOptions"
                            :key="item.dictCode"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="答案" prop="varAnswer">
                    <!-- <el-input
                        v-model="form.varAnswer"
                        placeholder="请输入答案"
                    /> -->
                    <el-select
                        v-if="form.chrType == 2 || form.chrType == '多选题'"
                        v-model="form.varAnswer"
                        multiple
                        placeholder="请选择"
                        style="width:100%;"
                    >
                        <el-option
                            v-for="item in form.varContent.options"
                            :key="item.item"
                            :label="item.item"
                            :value="item.item"
                        >
                        </el-option>
                    </el-select>
                    <el-select
                        v-else
                        v-model="form.varAnswer"
                        placeholder="请选择"
                        style="width:100%;"
                    >
                        <el-option
                            v-for="item in form.varContent.options"
                            :key="item.item"
                            :label="item.item"
                            :value="item.item"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="试题解析" prop="varAnalysis">
                    <el-input
                        type="textarea"
                        v-model="form.varAnalysis"
                    ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 用户导入对话框 -->
        <el-dialog
            :title="upload.title"
            :visible.sync="upload.open"
            width="400px"
            append-to-body
        >
            <el-upload
                ref="upload"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                :data="uploadData"
                drag
            >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                </div>
                <div class="el-upload__tip" slot="tip">
                    <el-link
                        type="info"
                        style="font-size:12px"
                        @click="importTemplate"
                        >下载模板</el-link
                    >
                </div>
                <div class="el-upload__tip" style="color:red" slot="tip">
                    提示：仅允许导入“xls”或“xlsx”格式文件！
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm"
                    >确 定</el-button
                >
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listCourseQuestion, getQuestion, delCourseQuestion, addQuestion, updateQuestion, exportQuestion, exportTemplate } from "@/api/system/question";
import { getToken } from "@/utils/auth";
export default {
    name: "courseQuestion",
    data () {
        const maxLength = (rule, value, callback) => {
            if (value.length > 200) {
                callback(new Error('试题解析字数不能超过200字'));
            } else {
                callback();
            }
        };
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            deleteNames: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 试题管理表格数据
            questionList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/system/question/importData"
            },
            uploadData: {
                courseId: ''
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                courseId: '',
                varTitle: '',
                chrType: ''
            },
            // 表单参数
            form: {
                courseId: '',
                varNo: undefined,
                // varTitle: undefined,
                varContent: {
                    title: '',
                    options: []
                },
                // chrCategory: undefined,
                chrType: undefined,
                varIndustry: undefined,
                varAnswer: '',
                varAnalysis: ''
            },
            // 表单校验
            rules: {
                // varNo: [
                //     { required: true, message: "试题编号不能为空", trigger: "blur" }
                // ],
                // varTitle: [
                //     { required: true, message: "题目内容不能为空", trigger: "blur" }
                // ],
                // chrCategory: [
                //     { required: true, message: "试题类型不能为空", trigger: "blur" }
                // ],
                chrType: [
                    { required: true, message: "题目类型不能为空", trigger: "blur" }
                ],
                varAnswer: [
                    { required: true, message: "题目答案不能为空", trigger: "blur" }
                ],
                varAnalysis: [
                    { validator: maxLength, message: "题目解析不能超过200字", trigger: "blur" }
                ],
                'varContent.title': [
                    { required: true, message: "题目标题不能为空", trigger: "blur" }
                ],
                'varContent.options[0].itemDesc': [
                    { required: true, message: "选项不能为空", trigger: "blur" }
                ]
            },
            varIndustryOptions: [], // 适用行业
            chrCategoryOptions: [], // 试题类型
            chrTypeOptions: [], // 题目类型
            jurisdiction: false
        };
    },
    activated () {
        this.initFn()
    },
    methods: {
        initFn () {
            this.queryParams.courseId = this.uploadData.courseId = this.$route.query.courseId
            this.jurisdiction = this.$route.query.jurisdiction
            this.getList();
            this.getDicts("var_industry").then(response => {
                this.varIndustryOptions = response.data;
            });
            this.getDicts("chr_category").then(response => {
                this.chrCategoryOptions = response.data;
            });
            this.getDicts("chr_type").then(response => {
                this.chrTypeOptions = response.data;
            });
        },
        chrTypeChange (val) {
            this.form.varAnswer = val == 2 ? [] : ''
        },
        dataFormat (val, options) {
            for (let i = 0; i < this[options].length; i++) {
                if (val == this[options][i].dictLabel) {
                    return this[options][i].dictValue
                }
            }
            return val
        },
        addOption () {
            this.form.varContent.options.push({
                item: '',
                itemDesc: ''
            })
            this.form.varContent.options.forEach((item, index) => {
                item.item = String.fromCharCode(64 + index + 1)
            })
        },
        /** 查询试题管理列表 */
        getList () {
            this.loading = true;
            listCourseQuestion(this.queryParams).then(response => {
                this.questionList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel () {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset () {
            this.form = {
                courseId: '',
                varNo: undefined,
                // varTitle: undefined,
                varContent: {
                    title: '',
                    options: []
                },
                // chrCategory: undefined,
                chrType: undefined,
                varIndustry: undefined,
                varAnswer: '',
                varAnalysis: ''
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.ids = selection.map(item => item.id)
            this.deleteNames = selection.map(item => item.varNo)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd () {
            this.reset();
            this.form.courseId = this.$route.query.courseId
            this.open = true;
            this.title = "新增试题管理";
        },
        /** 修改按钮操作 */
        handleUpdate (row) {
            this.reset();
            const id = row.id || this.ids
            getQuestion(id).then(response => {
                for (const key in this.form) {
                    this.form[key] = response.data[key]
                }
                this.form.varContent = response.data.varContent ? JSON.parse(response.data.varContent) : {
                    title: '',
                    options: []
                }
                this.form.varAnswer = this.form.chrType == '多选题' ? this.form.varAnswer.split('') : this.form.varAnswer
                this.form.id = response.data.id
                this.open = true;
                this.title = "修改试题管理";
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.varContent.options.length < 2) {
                        this.$message({
                            message: '试题选项不能少于2个',
                            type: 'warning'
                        })
                        return false
                    } else if (this.dataFormat(this.form.chrType, 'chrTypeOptions') == 2 && this.form.varAnswer.length < 2) {
                        this.$message({
                            message: '多选题答案不能少于2个',
                            type: 'warning'
                        })
                        return false
                    } else if (this.dataFormat(this.form.chrType, 'chrTypeOptions') == 1 && this.form.varAnswer.length > 1) {
                        this.$message({
                            message: '单选题答案只能有一个',
                            type: 'warning'
                        })
                        return false
                    }
                    let params = Object.assign({}, this.form)
                    params.varContent = JSON.stringify(params.varContent)
                    params.varAnswer = typeof params.varAnswer === 'object' ? params.varAnswer.join('') : params.varAnswer
                    if (this.form.id != undefined) {
                        params.varIndustry = this.dataFormat(params.varIndustry, 'varIndustryOptions')
                        params.chrCategory = this.dataFormat(this.form.chrCategory, 'chrCategoryOptions')
                        params.chrType = this.dataFormat(this.form.chrType, 'chrTypeOptions')
                        updateQuestion(params).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            }
                        });
                    } else {
                        params.intDifficult = 1
                        addQuestion(params).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            }
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            const ids = row.id || this.ids;
            const names = row.varNo || this.deleteNames.join('，')
            this.$confirm('是否确认删除试题管理编号为"' + names + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                return delCourseQuestion(this.queryParams.courseId, ids);
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(function () { });
        },
        /** 导出按钮操作 */
        handleExport () {
            const queryParams = this.queryParams;
            this.$confirm('是否确认导出所有试题管理数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return exportQuestion(queryParams);
            }).then(response => {
                this.download(response.msg);
            }).catch(function () { });
        },
        /** 导入按钮操作 */
        handleImport () {
            this.upload.title = "试题导入";
            this.upload.open = true;
        },
        /** 下载模板操作 */
        importTemplate () {
            exportTemplate()
            // exportTemplate().then(response => {
            //     this.download(response.msg);
            // });
        },
        // 文件上传中处理
        handleFileUploadProgress (event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess (response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
            this.getList();
        },
        // 提交上传文件
        submitFileForm () {
            this.$refs.upload.submit();
        },
        deleteOption (index) {
            this.form.varContent.options.splice(index, 1)
            this.form.varContent.options.forEach((item, index) => {
                item.item = String.fromCharCode(64 + index + 1)
            })
        }
    }
};
</script>
